package com.baizhi.realm;


import com.baizhi.entity.LayuiResource;
import com.baizhi.entity.LayuiUser;
import com.baizhi.mapper.LayuiResourceMapper;
import com.baizhi.mapper.LayuiUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//指定shiro的数据源，shiro做认证时，到哪儿去查询用户信息
@Component
public class MyPermissionRealm extends AuthorizingRealm {
    //用户表的dao对象
    @Autowired
    private LayuiUserMapper userMapper;
    @Autowired
    private LayuiResourceMapper resourceMapper;

    //授权方法，判断用户有哪些权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        1.得到用户的账号
        String username = (String) principals.getPrimaryPrincipal();
//        2.查询该用户资源权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<LayuiResource> layuiResources = resourceMapper.selectResByUsername(username);
        //先过滤type为function的权限，再获取Resource类中的Permission属性，封装到list集合，交给shiro
        List<String> functions = layuiResources.stream().filter(o -> "function".equals(o.getType())).map(LayuiResource::getPermission).collect(Collectors.toList());

        info.addStringPermissions(functions);
        return info;
    }

    /**
     * 认证相关代码，判断用户名和密码是否能够登录成功
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

//        1.token中有输入的账号密码  能够获取到账号  可以通过账号查数据库中的信息
        String username = (String) token.getPrincipal();


//        2.获取数据库数据，把账号信息shiro。

        QueryWrapper<LayuiUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        LayuiUser user = userMapper.selectOne(wrapper);

        if(user!=null){
//        3.把数据库查出来的账号密码封装在info中  三个参数：账号  密码  当前类的名字

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),this.getName());

            return info;
        }
        return null;
    }
}
